package class02;

/**
 * 可以通过设置虚拟节点或者单独判断head 与给定值的判断
 */
public class Code06_DeleteNode {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static ListNode deleteNode(ListNode head, int val) {

//        if (null == head) {
//            return null;
//        }
//        while (head.val == val) {
//            head = head.next;
//        }

        while (null != head) {
            if (val != head.val) {
                break;
            }
            head = head.next;
        }

        ListNode pre = head;
        ListNode cur = head;


        while (null != cur) {
            if (val == cur.val) {
                pre.next = cur.next;
            } else {
                pre = cur;
            }
            cur = cur.next;
        }
        return head;
    }


    public static void printLinkedList(ListNode node) {
        System.out.print("Linked List: ");
        while (node != null) {
            System.out.print(node.val + " ");
            node = node.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        ListNode head1 = new ListNode(1);

        head1.next = new ListNode(2);
        head1.next.next = new ListNode(3);
        head1.next.next.next = new ListNode(4);
        head1.next.next.next.next = new ListNode(5);
        head1.next.next.next.next.next = new ListNode(6);
        head1.next.next.next.next.next.next = new ListNode(7);

        printLinkedList(deleteNode(head1, 2));


    }
}
